import { DatetimePicker, Popup } from '@antmjs/vantui';
import dayjs from 'dayjs';
import React, { useState } from 'react';

export default function useDateTimeSelector(props: { onConfirm: Function }) {
  const [show, setShow] = useState<boolean>(false);
  const formatter = React.useCallback(function (type, value) {
    if (type === 'year') {
      return `${value}年`;
    }

    if (type === 'month') {
      return `${value}月`;
    }

    if (type === 'day') {
      return `${value}日`;
    }
    if (type === 'hour') {
      return `${value}时`;
    }
    if (type === 'minute') {
      return `${value}分`;
    }

    return value;
  }, []);

  function renderNode() {
    return (
      <Popup show={show} position='bottom' round onClose={() => setShow(false)}>
        <DatetimePicker
          formatter={formatter}
          minDate={dayjs().toDate().getTime()}
          onCancel={() => setShow(false)}
          onConfirm={(e) => {
            props.onConfirm(dayjs(e.detail.value).format('YYYY-MM-DD HH:mm'));
            setShow(false);
          }}
          type='datetime'
          filter={(type, options) => {
            if (type === 'minute') {
              return options.filter((option) => Number(option) % 30 === 0);
            }
            return options;
          }}
        ></DatetimePicker>
      </Popup>
    );
  }
  return {
    open: () => setShow(true),
    renderNode,
  };
}
